from rest_framework import serializers
import re
from users.models import User


class AdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
        # 反序列化
        extra_kwargs = {
            'password': {
                'write_only': True,  # write_only表示该字段只参与反序列化过程
                'max_length': 20,
                'min_length': 8,
                'required': False
            },
            'username': {
                'max_length': 20,
                'min_length': 5
            }
        }

        # 手机号格式验证 单一字段验证

    def validate_mobile(self, value):
        if not re.match('1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机格式不匹配')
        return value

    def create(self, validated_data):
        # 1、调用父类
        admin = super().create(validated_data)
        # 2、密码加密
        admin.set_password(validated_data['password'])
        admin.is_staff = True
        admin.save()
        # 3、结果返回
        return admin